
<template>
    <div class="page-parent">
        <Header title="防遗忘包" left-arrow @click-left="back" />

        <div class="tabs">
            <Tabs v-model:active="curFogettingTab" @click="onForgettingTab">
                <Tab :title-class="curFogettingTab == 1 && 'active'" :name="1" title="全城方案"></Tab>
                <Tab :title-class="curFogettingTab == 2 && 'active'" :name="2" title="半城方案"></Tab>
                <Tab :title-class="curFogettingTab == 3 && 'active'" :name="3" title="选点方案"></Tab>
            </Tabs>
        </div>


        <div v-if="curFogettingTab !== 3" class="put-info">
            <!-- 投放基本信息 -->
            <div class="put-base-info">
                <div class="title">
                    您的投放基本信息
                </div>
                <selectRow :show-value="curShowCities" title="投放城市" @on-click="isShowCitySlector = true"></selectRow>
                <selectRow :show-value="curShowDate" title="开始时间" @on-click="isShowDateSlector = true"></selectRow>
                <putProcess
                    v-if="curShowDate !== '请选择'" :start-time="curShowDate" class="put-process"
                    @on-procss-array="onProcessArray"
                ></putProcess>
            </div>
            <!-- 投放策略 -->
            <div class="put-case">
                <LaunchStrategy
                    v-if="curProcessArray.length > 0" ref="stategyRef" :optimal="formData.optimal"
                    :strategy="checkStrategy" :form-list="formList" :table-data="tableData" @onActiveTab="onActiveTab"
                    @change-pin="changePin" @change-lcd="changeLcd" @change-frame="changeFrame"
                ></LaunchStrategy>
            </div>
        </div>

        <div v-else class="select-case">
            <SelectedTags :is-show-bottom="false" :is-show-header="false"></SelectedTags>
            <!-- <selectCase></selectCase> -->
        </div>
        <div class="bottom">
            <div class="total-amount">
                <span v-if="curTab === 1 && curFogettingTab != 3" class="amount">¥{{ formatNumber(totalPrice) }}</span>
                <span v-else class="amount">-</span>
                <span class="remark">（按刊例价的0.5折计算）</span>
            </div>
            <div class="cph-price">
                <span v-if="curTab === 1 && curFogettingTab != 3">CPH：</span>
                <span v-if="curTab === 1 && curFogettingTab != 3" class="price">{{ cph }}元/户/周</span>
                <!-- <Popover v-model:show="showPopover" theme="dark" placement="top-end">
                <div class="pop-content">
                    仅针对住宅类楼盘计算每户每周触达成本，您的投放策略覆盖{{ cphPremissNum }}个中高端住宅楼盘，其中{{ cphScreenNum }}个智能屏，{{ cphLcdNum }}个LCD
                </div>
                <template #reference>
                    <img src="@/assets/img/cph-tips.png" alt="">
                </template>
            </Popover> -->
            </div>
            <div class="fe-btns">
                <div :class="(curTab === 2 && curFogettingTab !== 3) && 'disable'" class="right" @click="onclickNext">
                    下一步
                </div>
            </div>
        </div>
    </div>

    <CityAreaSelector
        v-model:show="isShowCitySlector" :list="cityList" :selected="formData.cityCodes"
        @close="isShowCitySlector = false" @confirm="onCitySelect"
    ></CityAreaSelector>
    <my-calendar
        :default-date="formData.startDate" :is-show="isShowDateSlector" @confirm="onDateSelect"
        @close="isShowDateSlector = false"
    />
    <publishStrategySelecter
        :strategy-id="checkStrategy?.id" :show="isShowStrategySelector" :list="strategyList"
        @close="isShowStrategySelector = false" @confirm="onStragySelect"
    ></publishStrategySelecter>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch } from 'vue';
import selectRow from './components/selectRow.vue';
import CityAreaSelector from '@/components/CityAreaSelecter/index.vue';
import { ReturnData, TreeChildModel } from '@/components/CityAreaSelecter/city.module';
import putProcess from './components/putProcess.vue';
import LaunchStrategy from './components/LaunchStrategy.vue';
import type { StrategyItemModel } from '../brandBreakout/breakout.module';
import { useRouter } from 'vue-router';
import publishStrategySelecter from '@/components/PublishStrategySelecter/index.vue';
import { getCityTreeData } from '@/api/common';
import dayjs from 'dayjs';
import { strategySpecsItem, getStrategyStatistics, StrategyStatisticsReq, saveStrategySpecs } from '@/api/brandBreakout';
import { CoverNumberItemModel } from '@/views/home/home.module';
import { handleMediaResource } from '@/utils';
// import {getMediaNameByType } from '@/utils/filters';
// import { mediaTypeList } from '@/utils/consts';
import { IProcessInfo } from './preventForgeting';
import MyCalendar from '@/components/MyCalendar/index.vue';
import { useStore } from '@/store';
import { clearLoading, showLoading } from '@/api';
import Header from '@/components/Header/index.vue';
import { formatNumber } from '@/utils/filters';
import { Tabs, Tab } from 'vant';
// import selectCase from './components/selectCase.vue';
import SelectedTags from '../selectByTag/index.vue';


function back() {
    return false;
}



const curTab = ref(1); // 1：社区场景 2：商务场景
const cphFrame = ref(0);
const cphLcdNum = ref(0);
const cphPremissNum = ref(0);
const cphScreenNum = ref(0);

// const ABCList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

const formData = reactive({
    cityName: '',
    cityCodes: [] as string[],
    startDate: '',
    strategyId: '1',
    strategyName: '',
    projectId: '',
    mediaTypes: [] as number[],
    optimalMediaType: 1,
    optimal: false,
    pointSelectionMode: 1,
});

const strategyList = ref<StrategyItemModel[]>([]);
const curShowCities = ref('请选择');
const curShowDate = ref('请选择');

const cph = ref('0');
const totalPrice = ref('0.00');
const tableData = ref<CoverNumberItemModel[]>([]);

strategyList.value = [];

const isShowCitySlector = ref(false);
const isShowDateSlector = ref(false);
const isShowStrategySelector = ref(false);
const cityList = ref<TreeChildModel[]>();
const formList = ref<{ label: string; value: string }[]>([]);
const PinDuaFreInfo = {
    duration: 15,
    frequency: 300
};
const LcdDuaFreInfo = {
    duration: 15,
    frequency: 300
};
const frameInfo = {
    framePublishMethod: 1
};
let curProcessArray: IProcessInfo[] = [];

// 组装请求页面投放初始信息的参数
const handleStrategyParams = (mediaTypes: number[], isUseDefault = false) => {

    // 拆阶段
    const processInfo = curProcessArray;
    const strategySpecs: strategySpecsItem[] = [];
    mediaTypes.forEach((type: number) => {
        if (type === 1 || type === 2) {
            if (processInfo) {
                processInfo.forEach((processItem: IProcessInfo) => {
                    const { startTimeReal, endTime } = processItem;
                    let duration = type === 1 ? PinDuaFreInfo.duration : LcdDuaFreInfo.duration;
                    duration = isUseDefault ? 15 : duration;
                    let frequency = type === 1 ? PinDuaFreInfo.frequency : LcdDuaFreInfo.frequency;
                    frequency = isUseDefault ? 300 : frequency;
                    const strategyItem: strategySpecsItem = {
                        mediaType: type,
                        duration,
                        frequency,
                        startDate: startTimeReal,
                        endDate: endTime
                    };
                    strategySpecs.push(strategyItem);
                });
            }
        } else {
            processInfo?.forEach((processItem: IProcessInfo) => {
                const { startTimeReal, endTime } = processItem;
                const strategyItem: strategySpecsItem = {
                    mediaType: type,
                    framePublishMethod: isUseDefault ? 1 : frameInfo.framePublishMethod,
                    startDate: startTimeReal,
                    endDate: endTime
                };
                strategySpecs.push(strategyItem);
            });
        }
    });

    const params: StrategyStatisticsReq = {
        pointSelectionMode: formData.pointSelectionMode,
        businessScenario: curTab.value,
        projectId: formData.projectId,
        mediaTypes: formData.mediaTypes,
        cityCodes: formData.cityCodes,
        strategySpecs: strategySpecs,
        // optimalMediaType: formData.optimalMediaType,
    };
    return params;
};
const curFogettingTab = ref(3); // 1. 全城放遗忘 2.半城防遗忘 3.标签选点防遗忘
formData.pointSelectionMode = curFogettingTab.value;

// 获取页面展示数据
async function getStatistics(isDefault = false) {
    if (curTab.value === 2) {
        return;
    }
    if (curFogettingTab.value === 3) {
        return;
    }
    showLoading();
    const params: StrategyStatisticsReq = handleStrategyParams(formData.mediaTypes, isDefault);
    const res = await getStrategyStatistics(params).catch(() => undefined);
    clearLoading();
    if (res) {
        totalPrice.value = res.price;
        cph.value = res.cph?.value;
        cphFrame.value = res.cph.framePointNum;
        cphLcdNum.value = res.cph.lcdPointNum;
        cphScreenNum.value = res.cph.screenPointNum;
        cphPremissNum.value = res.cph.premisesNum;
        formData.optimal = res.optimal;
        formData.mediaTypes = res.mediaTypes;
        formData.pointSelectionMode = res.pointSelectionMode;
        tableData.value = handleMediaResource(res.mediaResource).filter(item => item.type !== 2);
    }
}

async function onActiveTab(val: object) {
    curTab.value = val as unknown as number;
    // console.log('---tabchange send');
    if (curTab.value === 1) {
        await getStatistics();
    }
}

function getMediaName(mediaTypes: number[], pointSelectionMode: number) {
    if (mediaTypes.length === 1) {
        if (mediaTypes[0] === 1) {
            if (pointSelectionMode === 1) {
                return '全城防遗忘';
            }
            if (pointSelectionMode === 2) {
                return '半城防遗忘';
            }
        }
        // 全部LCD 引爆
        if (mediaTypes[0] === 2) {
            return '全部LCD防遗忘';
        }
    } else if (mediaTypes.length === 2) {
        return '全部智能屏 + 全部LCD防遗忘';
    }
    return '';
}

// const getMediaDesc = (mediaTypes: number[], pointSelectionMode: number) => {
//     const isOnlyOne = mediaTypes.every(item => item === 1);
//     const isOnlyTwo = mediaTypes.every(item => item === 2);
//     const isOneAndTwo = mediaTypes.includes(1) && mediaTypes.includes(2);
//     if (isOnlyOne && pointSelectionMode === 1) {
//         return '策略说明：选择全部智能屏防遗忘';
//     }
//     if (isOnlyOne && pointSelectionMode === 2) {
//         return '策略说明：每个楼盘选择一半的智能屏防遗忘';
//     }
//     if (isOneAndTwo && pointSelectionMode === 1) {
//         return '策略说明：选择全城的智能屏与LCD防遗忘';
//     }
//     if (isOnlyTwo) {
//         return '策略说明：选择全部LCD防遗忘';
//     }
// };


const checkStrategy = ref<StrategyItemModel>();
// 当选择的投放阶段信息变化时，刷新本页投放信息
async function onProcessArray(val: IProcessInfo[]) {
    // console.log('----------');
    curProcessArray = val;
    await getStatistics();
    checkStrategy.value!.name = getMediaName(formData.mediaTypes, formData.pointSelectionMode);
}

const store = useStore();
const initData = () => {
    formData.projectId = store.state.app.home.projectId;
    formData.optimalMediaType = store.state.app.home.optimalMediaType;
    formData.mediaTypes = [Number(formData.optimalMediaType)];
    checkStrategy.value = {
        name: getMediaName(formData.mediaTypes, formData.pointSelectionMode),
        id: '',
        desc: '',
        mediaTypes: formData.mediaTypes
    };
    // 设置首页选中城市
    const city = store.state.app.home.selectCity;
    if (city) {
        formData.cityName = city.name;
        formData.cityCodes = [city.id];
    }
    // 设置默认开始日期
    const week = dayjs().day();
    if (week === 6) {
        formData.startDate = dayjs().day(6).add(1, 'week').format('YYYY-MM-DD');
    } else {
        formData.startDate = dayjs().day(6).format('YYYY-MM-DD');
    }
    curShowDate.value = formData.startDate;
    curShowCities.value = formData.cityName;
};
async function onCitySelect(value: ReturnData) {
    const len = value.nameList.length;
    formData.cityName = value.nameList.slice(0, 2).join('、') + (len > 2 ? `等${len}个城市` : '');
    formData.cityCodes = value.selected;
    curShowCities.value = formData.cityName;
    isShowDateSlector.value = false;
    await getStatistics();
}

function onDateSelect(data: Date) {
    // date.value = formatDate(value);
    formData.startDate = dayjs(data).format('YYYY-MM-DD');
    curShowDate.value = formData.startDate;
    isShowDateSlector.value = false;// 选中日期传给后台需要加上四周固定日期
    // await getStatistics();
}

const stategyRef = ref<{ resetSelect:() => void }>();
function resetPinLcdFrame() {
    // 这里重置 频次选择器
    PinDuaFreInfo.duration = 15;
    PinDuaFreInfo.frequency = 300;
    LcdDuaFreInfo.duration = 15;
    LcdDuaFreInfo.frequency = 300;
    frameInfo.framePublishMethod = 1;
    stategyRef.value?.resetSelect();
}

async function onStragySelect(data: StrategyItemModel) {
    formData.strategyName = data.name;
    formData.mediaTypes = data.mediaTypes || [];
    checkStrategy.value = data;
    formData.pointSelectionMode = data.pointSelectionMode || 0;
    resetPinLcdFrame();
    await getStatistics(true);
}



// const changeStrategy = async () => {
//     const params: StrategyStatisticsReq = handleStrategyParams(mediaTypeList.map(e => e.type), true);
//     try {
//         showLoading();
//         const res = await getStrategyStatisticsList(params);
//         console.log('res:', res);
//         if (res && res.length) {
//             strategyList.value = res.map((item: StrategyStatisticsRes, index: number) => {
//                 return {
//                     name: `策略${ABCList[index]}: ` + getMediaName(item.mediaTypes,item.pointSelectionMode),
//                     id: `${index}`,
//                     desc: getMediaDesc(item.mediaTypes, item.pointSelectionMode) as string,
//                     proList: item.mediaTypes.map(type => {
//                         return {
//                             name: getMediaNameByType(type),
//                             amount: item.mediaResource?.mediaResourceSummaryList?.find(e => e.mediaType === type)?.pointNum || 0,
//                             unit: type === 3 ? '个' : '台'
//                         };
//                     }),
//                     total: item.price,
//                     cph: item.cph?.value,
//                     optimal: item.optimal,
//                     mediaTypes: item.mediaTypes,
//                     pointSelectionMode: item.pointSelectionMode,
//                     coveredPeopleNum: item.mediaResource?.resourceSummary?.coveredPeopleNum,
//                 };
//             });
//             if (!checkStrategy.value?.id) {
//                 checkStrategy.value = strategyList.value.find(item => JSON.stringify(item.mediaTypes?.sort()) === JSON.stringify(formData.mediaTypes?.sort()));
//             }
//         }
//     } catch (error) {
//         console.log(error);
//     } finally {
//         clearLoading();
//     }
// };
// // 点击调整策略
// async function selectStrategy() {

//     isShowStrategySelector.value = true;
//     await changeStrategy();
// }
async function changePin(data: { duration: string, frequency: string }) {
    PinDuaFreInfo.duration = +data.duration.slice(0, data.duration.length - 1);
    PinDuaFreInfo.frequency = +data.frequency.slice(0, data.frequency.length - 1);
    await getStatistics();
}
async function changeLcd(data: { duration: string, frequency: string }) {
    LcdDuaFreInfo.duration = +data.duration.slice(0, data.duration.length - 1);
    LcdDuaFreInfo.frequency = +data.frequency.slice(0, data.frequency.length - 1);
    await getStatistics();
}
async function changeFrame(data: { framePublishMethod: number }) {
    frameInfo.framePublishMethod = +data.framePublishMethod;
    await getStatistics();
}

const router = useRouter();
async function onclickNext() {
    const params: StrategyStatisticsReq = handleStrategyParams(formData.mediaTypes);
    await saveStrategySpecs(params);

    if (curFogettingTab.value === 3) {
        await router.push({
            name: 'selectByTagMap',
            query: {
                isFromForgetting: 1
            }
        });
    } else {
        await router.push({
            name: 'productsBrandBreakoutResult',
            query: {
                type: 6
            }
        });
    }
}

function onForgettingTab(val: number) {
    formData.pointSelectionMode = val;
}

watch(() => curFogettingTab.value, async (newVal: number, oldVal: number) => {
    if (oldVal !== 3) {
        await getStatistics();
        checkStrategy.value!.name = getMediaName(formData.mediaTypes, formData.pointSelectionMode);
    }
});

onMounted(async () => {
    // console.log('---initdata');
    initData();
    cityList.value = await getCityTreeData(0);
    // await onForgettingTab(curFogettingTab.value);
});


</script>

<style lang="scss" scoped>
@import "@/styles/variables";

.page-parent {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    height: 100vh;
    background: #f4f4f4;

    .tabs {
        position: relative;
        z-index: 99;

        :deep(.van-tabs) {
            [class~="van-tabs__wrap"] {
                // padding-top: 10px;
                height: 48px;
            }

            [class~="van-tab"] {
                padding-top: 4px;
            }

            .van-tab.active {
                span {
                    color: #e60044 !important;
                }
            }
        }
    }
}

.put-info {
    flex: 1;
    overflow: auto;
    padding: 12px;
    // padding-bottom: 128px;

    .put-base-info {
        box-sizing: border-box;
        width: 351px;
        background: #fff;
        border-radius: 10px;
        margin: auto;
        padding: 12px;
        padding-bottom: 16px;
        padding-top: 16px;

        .title {
            color: #333333;
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
        }

        .put-process {
            margin-top: 15px;
        }
    }
}

.select-case {
    flex: 1;
    overflow: auto;

    :deep(.header) {
        display: none;
    }

    :deep(.footer) {
        display: none;
    }

    :deep(.card-info) {
        .card {
            margin-bottom: 0;
        }
    }
}

.bottom {
    background: #ffffff;
    width: 100%;
    border-top: 0.5px solid #f4f4f4;
    padding: 12px 0 8px;
    padding-bottom: contain(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    overflow: hidden;
    box-sizing: border-box;
    box-shadow: 0 -2px 4px 0 #ebebeb80;

    div {
        display: flex;
        padding: 0 12px;

        span {
            display: inline-block;
            font-weight: 400;
            font-size: 12px;
            color: #5b5b5b;
            height: 17px;
        }
    }

    .total-amount {
        justify-content: flex-end;
        align-items: center;

        .amount {
            height: 21px;
            line-height: 21px;
            font-family: $spec_font;
            font-size: 18px;
            color: #e60044;
            text-align: right;
        }

        .remark {
            height: 21px;
            line-height: 21px;
        }
    }

    .cph-price {
        margin-top: 3px;
        justify-content: flex-end;
        align-items: center;

        .price {
            height: 17px;
            font-weight: 600;
            font-size: 12px;
            color: #333333;
            margin-right: 6px;
        }

        img {
            width: 14px;
            height: 14px;
        }
    }

    .fe-btns {
        margin-top: 12px;
        border-top: 0.5px solid #f4f4f4;
        display: flex;
        padding: 6px 12px 0;
        margin-bottom: 8px;

        div {
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .left {
            width: 120px;
            height: 38px;
            line-height: 38px;
            background: #ffffff;
            border: 0.5px solid #e60044;
            border-radius: 6px;
            font-weight: 400;
            font-size: 14px;
            color: #e60044;
            text-align: center;
            margin-right: 12px;
        }

        .right {
            width: 100%;
            height: 38px;
            line-height: 38px;
            background: #e60044;
            border: 0.5px solid #e60044;
            border-radius: 6px;
            font-weight: 600;
            font-size: 14px;
            color: #ffffff;
            text-align: center;
        }

        .right.disable {
            opacity: 0.7;
            pointer-events: none;
        }

        .left.disable {
            opacity: 0.7;
            pointer-events: none;
        }
    }
}
</style>
